<template>
    <div class="about-page">
      <h1>运动建议</h1>
      <div v-if="loading" class="loading text-center mt-4">
        <i class="fa fa-spinner fa-spin mr-2"></i> 加载中...
      </div>
      <div v-else>
        <table>
          <thead>
            <tr>
              <th>content（内容）</th>
              <th>created_at（创建时间）</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(advice, index) in advices" :key="index">
              <td>{{ advice.content }}</td>
              <td>{{ formatDate(advice.created_at) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </template>
  
  <script setup>
  import axios from 'axios';
  import { ref, onMounted } from 'vue';
  import { useUserStore } from '@/stores/counter'; // 引入用户store
  
  const userStore = useUserStore();
  const advices = ref([]);
  const loading = ref(true);
  
  // 格式化日期函数
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  };
  
  onMounted(async () => {
    const user_id = userStore.userId;
    if (!user_id) {
      console.error('用户未登录，无法获取运动建议');
      alert('请先登录');
      return;
    }
  
    try {
      const response = await axios.get('http://localhost:8080/MDMS0214_war/exerciseAdvice/all');
      if (response.status === 200) {
        const filteredAdvices = response.data.filter(advice => advice.user_id === user_id);
        advices.value = filteredAdvices;
      } else {
        console.error('获取运动建议接口返回非200状态码:', response.status);
        alert('获取运动建议失败，请稍后重试');
      }
    } catch (error) {
      console.error('获取运动建议失败:', error);
      alert('获取运动建议失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  });
  </script>
  
  <style scoped>
  .about-page {
    font-family: Arial, sans-serif;
    padding: 20px;
  }
  
  table {
    border-collapse: collapse;
    width: 100%;
    background-color: rgba(255, 255, 255, 0.8); /* 添加半透明白色背景 */
  }
  
  th, td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
  }
  
  h1 {
    text-shadow: 0 0 5px white; /* 添加文字阴影，让标题更清晰 */
  }
  
  .loading {
    font-size: 18px;
  }
  </style>